<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6">
            <a-form-model-item label="物料编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入物料编码" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="17">
            <a-form-model-item
              label="物料种类"
              :labelCol="{ xs: { span: 24 }, sm: { span: 3 }, style: 'width: 10%;' }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 18 } }"
              prop="categoryName"
            >
              <a-row :gutter="5">
                <a-col :span="6">
                  <a-input v-model="model.categoryNo" disabled placeholder="种类编号"></a-input>
                </a-col>
                <a-col :span="17">
                  <j-select-goods-category
                    ref="selectGoodsCategory"
                    v-model="model.categoryName"
                    @onGoodsCategorySelected="onGoodsCategorySelected"
                  />
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户物料编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customCode">
              <a-input v-model="model.customCode" placeholder="请输入客户物料编号"></a-input>
            </a-form-model-item>
          </a-col>
<!--
          <a-col :span="6" v-if="packageShow || productShow">
            <a-form-model-item label="品牌/标识" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <a-input v-model="model.brand" @blur="nameChange" placeholder="请输入品牌/标识"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="packageShow || productShow">
            <a-form-model-item label="品名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="itemName">
              <a-row :gutter="5">
                <a-col :span="12">
                  <a-input v-model="model.itemName" @blur="nameChange" placeholder="请输入品名"></a-input>
                </a-col>
                <a-col :span="12">
                  <j-dict-select-tag
                    type="list"
                    v-model="model.itemName"
                    dictCode="tsl_item_name"
                    @change="nameChange"
                    placeholder="请选择"
                  />
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="packageShow || productShow">
            <a-form-model-item label="香型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flavor">
              <a-input v-model="model.flavor" @blur="nameChange" placeholder="请输入香型"></a-input>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-model-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="noneSpec">
              <a-input v-model="model.noneSpec" @blur="noneSpecChange" placeholder="xxxKG*数字格式填写"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入物料名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="meUnit">
              <j-dict-select-tag type="list" v-model="model.meUnit" dictCode="ji_unit" placeholder="请选择单位" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="辅单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="auUnit">
              <j-dict-select-tag
                type="list"
                v-model="model.auUnit"
                dictCode="zl_unit"
                placeholder="请选择辅单位"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="换算率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="coRate">
              <a-input v-model="model.coRate" placeholder="请输入换算率"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="仓储仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseName">
              <erp-warehouse
                ref="erpWarehouse"
                v-model="model.warehouseName"
                @onWarehouseSelected="onWarehouseSelected"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="packageShow">
            <a-form-model-item label="材质" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialQuality">
              <a-input v-model="model.materialQuality" placeholder="请输入材质"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="packageShow">
            <a-form-model-item label="尺寸" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="size">
              <a-input v-model="model.size" placeholder="请输入尺寸"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="packageShow">
            <a-form-model-item
              label="袋型(包材种类)"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="packageCategory"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.packageCategory"
                dictCode="bc_type"
                placeholder="请选择包材种类"
                @change="nameChange"
              />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="6">
            <a-form-model-item label="物料描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryDescription">
              <a-input v-model="model.categoryDescription" placeholder="请输入物料描述"></a-input>
            </a-form-model-item>
          </a-col>-->
<!--          <a-col :span="6" v-if="productShow">
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="classify">
              <j-dict-select-tag type="list" v-model="model.classify" dictCode="formula_desc" placeholder="请选择类型" />
            </a-form-model-item>
          </a-col>-->
          <a-col :span="6" v-if="productShow">
            <a-form-model-item label="包装方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageType">
              <a-input v-model="model.packageType" @blur="nameChange" placeholder="请输入包装方式"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="productShow ">
            <a-form-model-item label="最小包装量（g）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packSpec">
              <a-input v-model="model.packSpec" :min="1" placeholder="请输入最小包装量（g）" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="productShow">
            <a-form-model-item label="最小包装量个数/单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packSpecNum">
              <a-input v-model="model.packSpecNum" :min="1" placeholder="请输入最小包装量个数/单位" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="保质期（天）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="qualityDays">
              <a-input v-model="model.qualityDays" placeholder="保质期（天）"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="允许呆滞时长（天）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sluggishHours">
              <a-input v-model="model.sluggishHours" placeholder="允许呆滞时长（天）"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="允许最小库存" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="minimumInventory">
              <a-input-number v-model="model.minimumInventory" placeholder="请输入允许最小库存" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="允许最大库存" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="maxInventory">
              <a-input-number v-model="model.maxInventory" placeholder="请输入允许最大库存" style="width: 100%" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="6" v-if="productShow">
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <a-input-search
                v-model="model.customerName"
                placeholder="请选择客户"
                readonly
                enter-button
                @search="handleSelectCustomer1"
                :disabled="formDisabled"
              ></a-input-search>
              <a-input v-model="model.customerId" hidden></a-input>
            </a-form-model-item>
          </a-col>-->
          <a-col :span="6" >
            <a-form-model-item label="物料分类1" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerName">
              <j-dict-select-tag type="list" v-model="model.customerName" @blur="nameChange" placeholder="请选择物料分类1" dictCode="material_classification_fir"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="物料分类2" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <j-dict-select-tag  type="list"  v-model="model.brand" @blur="nameChange" placeholder="请选择物料分类2" dictCode="material_classification_sen"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="productShow">
            <a-form-model-item label="单位/Tray" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unitTray">
              <a-input v-model="model.unitTray" placeholder="请输入单位/Tray"></a-input>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="6">
            <a-form-model-item label="安全库存" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="stockQuantity">
              <a-input-number v-model="model.stockQuantity" :min="0" placeholder="请输入安全库存" style="width: 100%" />
            </a-form-model-item>
          </a-col>-->

<!--          <a-col :span="6">
            <a-form-model-item label="最大收货比率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="stockQuantity">
              <a-input-number
                v-model="model.receiveRate"
                :min="0"
                placeholder="请输入最大收货比率"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>-->
          <!-- <a-col :span="8">
            <a-form-model-item label="配方号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaNo">
              <a-input v-model="model.formulaNo" disabled placeholder="请输入配方号"></a-input>
            </a-form-model-item>
          </a-col> -->
<!--          <a-col :span="6">
            <a-form-model-item label="是否领料" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isUse">
              <j-dict-select-tag type="list" v-model="model.isUse" dictCode="yes_no" placeholder="请选择是否领料" />
            </a-form-model-item>
          </a-col>-->

          <!-- <a-col :span="12">
            <a-form-model-item label="条形码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="barCode">
              <a-input v-model="model.barCode" placeholder="请输入条形码"></a-input>
            </a-form-model-item>
          </a-col> -->
<!--          <a-col :span="6" v-if="productShow">
            <a-form-model-item label="配方保密" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isUse">
              <j-dict-select-tag type="list" v-model="model.isUse" dictCode="yes_no" placeholder="请选择是否领料" />
            </a-form-model-item>
          </a-col>-->
          <Tsl-Select-Customer-Single ref="selectCustomerModal1" @selectFinished="selectOK"></Tsl-Select-Customer-Single>
<!--          <a-col :span="6">
            <a-form-model-item
              label="客户物料类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="customGoodsType"
            >
              <a-input v-model="model.customGoodsType" placeholder="请输入客户物料类型"></a-input>
            </a-form-model-item>
          </a-col>-->

<!--          <a-col :span="6">
            <a-form-model-item
              label="供应商要求名称"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierRequireName"
            >
              <a-input v-model="model.supplierRequireName" placeholder="请输入供应商要求名称"></a-input>
            </a-form-model-item>
          </a-col>-->
<!--          <a-col :span="6">
            <a-form-model-item label="在途天数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="onRoadDays">
              <a-input v-model="model.onRoadDays" placeholder="在途天数"></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="库存数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inventoryQuantity">
              <a-input-number v-model="model.inventoryQuantity" placeholder="请输入库存数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>-->
          <!-- <a-col :span="12">
            <a-form-model-item label="物料种类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryCode">
              <j-dict-select-tag type="list" v-model="model.categoryCode"
                                 dictCode="erp_goods_category,name,id" placeholder="请选择物料种类"/>
            </a-form-model-item>
          </a-col> -->
          <!-- <a-col :span="6">
            <a-form-model-item label="是否有版样" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isPattern">
              <j-dict-select-tag
                type="list"
                v-model="model.isPattern"
                dictCode="yes_no"
                placeholder="请选择是否有版样"
              />
            </a-form-model-item>
          </a-col> -->
<!--          <a-col :span="6" v-if="productShow">
            <a-form-model-item
              label="是否关联包材"
              :labelCol="{ xs: { span: 24 }, sm: { span: 6 }, style: 'width: 40%;' }"
              :wrapperCol="{ xs: { span: 24 }, sm: { span: 10 } }"
              prop="isAssBc"
            >
              <j-dict-select-tag
                type="list"
                v-model="model.isAssBc"
                dictCode="yes_no"
                placeholder="请选择是否关联包材"
                @change="onChangeShowRow"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="6">
            <a-form-model-item label="是否启用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="useStatus">
              <j-dict-select-tag
                type="list"
                v-model="model.useStatus"
                dictCode="erp_status"
                placeholder="请选择是否启用"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="packageShow">
            <a-form-model-item label="是否公用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isPublic">
              <j-dict-select-tag type="list" v-model="model.isPublic" dictCode="yes_no" placeholder="请选择是否公用" />
            </a-form-model-item>
          </a-col>-->
          <!--v-if="packageShow||productShow"-->
<!--          <a-col :span="6">
            <a-form-model-item label="所属人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="belongUser">
              <a-row :gutter="4">
                <a-col :span="18">
                  <a-input v-model="model.belongUser" placeholder="请选择所属人员"></a-input>
                </a-col>

                <a-col :span="6">
                  <a-button @click="handleSelectEmployee" type="primary" :loading="confirmLoading">选择员工</a-button>
                </a-col>
              </a-row>
            </a-form-model-item>
          </a-col>-->
<!--          <a-col :span="6" v-if="packageShow">
            <a-form-model-item label="比例数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proportion">
              <a-input type="number" v-model="model.proportion" placeholder="请输入比例数量"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" v-if="packageShow">
            <a-form-model-item label="颜色" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="background">
              <a-input v-model="model.background" placeholder="请输入颜色"></a-input>
            </a-form-model-item>
          </a-col>-->
          <!-- <a-col :span="6" v-if="packageShow">
            <a-form-model-item label="版样编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="patternCode">
              <a-input v-model="model.patternCode" disabled placeholder="请输入材质"></a-input>
            </a-form-model-item>
          </a-col> -->
<!--          <a-col :span="6" v-if="packageShow || productShow">
            <a-form-model-item label="以前的订单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="historyOrder">
              <a-input v-model="model.historyOrder" disable></a-input>
            </a-form-model-item>
          </a-col>-->
        </a-row>
<!--        <a-row v-if="packageShow">
          <a-form-model-item
            label="包装要求"
            :labelCol="textareaLabelCol"
            :wrapperCol="textareaWrapperCol"
            prop="packRequire"
          >
            <a-textarea v-model="model.packRequire" rows="4" placeholder="请输入备注" />
          </a-form-model-item>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="textareaLabelCol" :wrapperCol="textareaWrapperCol" prop="remark">
              <a-textarea v-model="model.remark" rows="2" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>-->
<!--        <a-divider v-if="packageShow">版样</a-divider>-->
<!--        <a-row v-if="packageShow">
          <a-col :span="24">
            <j-upload v-model="model.patternFile" text="版样"></j-upload>
          </a-col>
        </a-row>-->
        <a-row v-if="productShow">
          <a-tabs :default-active-key="tabkeys[0]">
<!--            &lt;!&ndash; 子表单区域 &ndash;&gt;-->
            <a-tab-pane :key="tabkeys[0]" tab="包材">
              <a-row :gutter="1">
<!--                &lt;!&ndash; 新增 &ndash;&gt;-->
                <a-col :span="24">
                  <a-button type="primary" icon="" size="small" @click="addMaterielPackage"> 选择包材 </a-button>
                  <erp-goods-list-model
                    ref="selectGoodsList"
                    :modalWidth="modalWidth"
                    :category="category"
                    @goodsOk="goodsOk"
                    checkval="checkbox"
                  >
                  </erp-goods-list-model>
                  <a-divider type="vertical" />
                  <a-button type="primary" icon="" size="small" @click="newMaterielPackage">新增包材 </a-button>
                  <erp-goods-package-modal ref="addGoodsPackage" @goodsOk="goodsOk" @updateOk="updatePackageOk">
                  </erp-goods-package-modal>
                </a-col>
                <a-col :span="24">
<!--                  &lt;!&ndash; 表格 &ndash;&gt;-->
                  <a-table
                    bordered
                    :data-source="model.erpGoodsPackageList"
                    :columns="materielColumns"
                    :rowKey="(record) => record.packageId"
                    :pagination="false"
                  >
                    <template slot="proportion" slot-scope="text, record">
                      <edit-number-cell-2
                        :text="text"
                        @change="onCellChange(record, 'proportion', $event)"
                      ></edit-number-cell-2>
                    </template>
                    <template slot="packageInOutType" slot-scope="text, record">
                      <a-select :value="text" @change="onCellChange(record, 'packageInOutType', $event)">
                        <a-select-option
                          v-for="item in packageTypeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                          {{ item.label }}
                        </a-select-option>
                      </a-select>
                    </template>
                    <template slot="operation" slot-scope="text, record">
                      <a @click="onEditPackage(record)">编辑</a>
                      <a-divider type="vertical" />
                      <a-popconfirm title="确认删除?" @confirm="() => onDelete(record.packageId)">
                        <a href="javascript:;">删除</a>
                      </a-popconfirm>
<!--                      &lt;!&ndash;<a @click="handleEdit(record)">保存</a>&ndash;&gt;-->
                    </template>
                  </a-table>
                </a-col>
              </a-row>
            </a-tab-pane>
            <a-tab-pane :key="tabkeys[1]" tab="配方" force-render>
              <a-row :gutter="10">
                <a-col :span="2">
                  <a-button
                    type="primary"
                    icon=""
                    size="small"
                    @click="conFormular"
                    >关联BOM</a-button
                  >
                  <erp-goods-formular-con-modal @formularOk="formularOk" ref="formularCon" />
                </a-col>
              </a-row>
              <a-row>
                <a-col :span="24">
                  &lt;!&ndash; 表格 &ndash;&gt;
                  <a-table
                    ref="table"
                    size="middle"
                    :scroll="{ x: true }"
                    bordered
                    rowKey="id"
                    :columns="formulaTable.formulaColumn"
                    :dataSource="formulaTable.datasource"
                    :pagination="formulaTable.ipagination"
                    :rowSelection="{ onChange: onSelectChange, selectedRow: onSelectRow }"
                    :loading="formulaTable.loading"
                    class="j-table-force-nowrap1"
                  >
                    <template slot="num" slot-scope="text, record">
                      <editable-cell-2 :text="text" @change="onCellChange(record, 'num', $event)"></editable-cell-2>
                    </template>
                    <template slot="operation" slot-scope="text, record">
                      <a-popconfirm title="确认删除?" @confirm="() => onDelete(record.packageId)">
                        <a href="javascript:;">删除</a>
                      </a-popconfirm>
                      &lt;!&ndash;                <a @click="handleEdit(record)">保存</a>&ndash;&gt;
                    </template>
                  </a-table>
                </a-col>
              </a-row>
            </a-tab-pane>
          </a-tabs>
        </a-row>
      </a-form-model>
    </j-form-container>
    <employee-list-modal ref="selectEmployee" @handleOk="handleSelectEmployeeOk" />
    <select-erp-goods-modal ref="selectGoodsList" @Ok="referOk" />
  </a-spin>
</template>

<script>
import { httpAction } from '@/api/manage'
import { putAction } from '@api/manage'
import { postAction } from '@api/manage'
import { getAction } from '@api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import ErpGoodsListModel from '@comp/base/modal/ErpGoodsListModal'
import EditableCell2 from '@comp/table/EditableCell2'
import EmployeeListModal from '@/components/tsl/modules/EmployeeListModal.vue'
import ErpGoodsPackageModal from './ErpGoodsPackageModal.vue'
import EditNumberCell2 from '../../../../components/table/EditNumberCell2.vue'
import ErpGoodsFormularConModal from '../../../../components/tsl/modules/ErpGoodsFormularConModal.vue'
import store from '@/store'
import TslSelectCustomerSingle from '@views/erp/goods/modules/TslSelectCustomerSingle.vue'
import SelectErpGoodsModal from '@views/erp/goods/modules/SelectErpGoodsModal.vue'
import { assign } from 'min-dash'

export default {
  name: 'ErpGoodsForm',
  components: {
    ErpGoodsListModel,
    EditableCell2,
    EmployeeListModal,
    ErpGoodsPackageModal,
    EditNumberCell2,
    ErpGoodsFormularConModal,
    TslSelectCustomerSingle,
    SelectErpGoodsModal
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      productShow: false,
      otherShow: false,
      packageShow: false,
      switchValue: false,
      visible: false,
      modalWidth: 1250,
      category: '2',
      packageTypeOptions: [],
      tabkeys: ['material', 'uphistorys'],
      model: {
        id: '',
        code: '',
        categoryName: '',
        categoryNo: '',
        useStatus: 1,
        isUse: 1,
        isPublic: 1,
        isAssBc: 1,
        isPattern: 1,
        noneSpec: '',
        packSpec: 0,
        meUnit: '',
        auUnit: '1',
        customCode: '',
        coRate: 0,
        barCode: '',
        formulaNo: '',
        belongUser: '',
        packageType: '',
        onRoadDays: '',
        size: '',
        materialQuality: '',
        packRequire: '',
        packageCategory: '',
        warehouseCode: '',
        warehouseName: '',
        receiveRate: '100',
        erpGoodsPackageList: [],
      },
      materielColumns: [
        {
          title: '包材编号',
          dataIndex: 'packageCode',
        },
        {
          title: '包材名称',
          dataIndex: 'packageName',
        },
        {
          title: '规格型号',
          dataIndex: 'noneSpec',
        },
        {
          title: '包材类别',
          dataIndex: 'packageInOutType',
          scopedSlots: { customRender: 'packageInOutType' },
          width: 150,
        },
        {
          title: '数量比例',
          dataIndex: 'proportion',
          scopedSlots: { customRender: 'proportion' },
          width: 150,
        },
        {
          title: '袋型(包材种类)',
          dataIndex: 'packageCategory',
        },
        {
          title: '品名',
          dataIndex: 'itemName',
        },
        {
          title: '品牌',
          dataIndex: 'brand',
        },
        {
          title: '香型',
          dataIndex: 'flavor',
        },
        {
          title: '材质',
          dataIndex: 'materialQuality',
        },
        {
          title: '颜色',
          dataIndex: 'background',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        style: 'width: 30%;',
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      textareaLabelCol: {
        xs: { span: 12 },
        sm: { span: 2 },
      },
      textareaWrapperCol: {
        xs: { span: 40 },
        sm: { span: 21 },
      },
      confirmLoading: false,
      validatorRules: {
        code: [{ required: true, message: '请输入编号!' }],
        // name: [{ required: true, message: '请输入名称!',trigger:'blur' }],
        noneSpec: [{ required: true, message: '请输入规格!' }],
        packSpec: [{ required: false, message: '请输入包装规格(g)!' }],
        categoryName: [{ required: true, message: '请输入物料种类!' }],
        customCode: [{ required: false, message: '请输入客户物料编号!' }],
        meUnit: [{ required: true, message: '请输入计量单位!' }],
        auUnit: [{ required: true, message: '请选择辅单位' }],
        useStatus: [{ required: true, message: '请输入状态!' }],
        coRate: [{ required: true, message: '请输入转化率' }],
        classificationId: [{ required: true, message: '请输入物料分类!' }],
        isPattern: [{ required: false, message: '请输入是否有版样!' }],
        stockQuantity: [{ required: false, message: '请输入安全库量!' }],
        inventoryQuantity: [{ required: false, message: '请输入库存数量!' }],
        warehouseCode: [{ required: true, message: '请输入所属仓库!' }],
        isAssBc: [{ required: false, message: '请输入是否关联包材!' }],
        isPublic: [{ required: false, message: '请输入是否公用!' }],
        isUse: [{ required: false, message: '请输入是否领料!' }],
      },

      //配方列表column
      formulaTable: {
        loading: false,
        datasource: [],
        // 表头
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['10', '30', '100'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
        formulaColumn: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: 'BOM版本',
            dataIndex: 'year',
          },
          {
            title: 'BOM编码',
            dataIndex: 'code',
          },
          {
            title: 'BOM号',
            dataIndex: 'no',
          },

          {
            title: 'BOM名称',
            dataIndex: 'name',
          },
          {
            title: 'BOM类别',
            dataIndex: 'category_dictText',
          },
          {
            title: '制单人',
            dataIndex: 'createByName',
            width: 150,
          },
          {
            title: '制单日期',
            dataIndex: 'createTime',
          },
          {
            title: 'BOM类型',
            dataIndex: 'type_dictText',
          },
        ],
      },
      url: {
        add: '/base/erpGoods/add',
        edit: '/base/erpGoods/edit',
        queryById: '/base/erpGoods/queryById',
      },
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    initDictOptions('package_type').then((res) => {
      if (res.success) {
        this.packageTypeOptions = res.result
      }
    })
  },
  methods: {
    referOk(row){
      console.log("aaaaaaahhhhhhhhh",row)
      this.model = JSON.parse(JSON.stringify(row));
      this.model.id=null
    },
    handleRefer(){
      console.log("aaaaaaaaaaaaaaaaaaaaa")
      this.$refs.selectGoodsList.visible = true
    },
    handleSelectCustomer1() {
      this.$refs.selectCustomerModal1.visible = true
    },
    selectOK(data) {
      this.$set(this.model,"customerName",data.name)
      this.model.customerName = data.name
      this.model.customerId = data.id
    },
    nameChange() {
      if (this.productShow) {
        let name = this.model.brand ? this.model.brand : ''
        if (this.model.itemName) {
          name += this.model.itemName
        }
        if (this.model.flavor) {
          name += this.model.flavor
        }
        if (this.model.noneSpec) {
          name += this.model.noneSpec
        }
        if (this.model.packageType) {
          name += this.model.packageType
        }
        this.model.name = name
        this.$forceUpdate()
      } else if (this.packageShow) {
        let name = this.model.brand ? this.model.brand : ''
        if (this.model.itemName) {
          name += this.model.itemName
        }
        if (this.model.flavor) {
          name += this.model.flavor
        }
        if (this.model.packageCategory) {
          name += this.model.packageCategory
        }
        if (this.model.noneSpec) {
          name += this.model.noneSpec
        }

        this.model.name = name
        this.$forceUpdate()
      }
    },
    conFormular() {
      let good = {
        id: this.model.id,
        code: this.model.code,
        name: this.model.name,
      }
      this.$refs.formularCon.add([good])
      this.$refs.formularCon.title = '关联BOM'
      this.$refs.formularCon.disableSubmit = false
    },
    formularOk(data) {
      console.log('关联BOM', data)
      this.getFormulas();
    },
    getGoodsCode() {
      let url = '/sys/fillRule/executeRuleByCode/material_code'
      let param = { inputCharacter: 'M' }
      if (this.productShow) {
        param = { inputCharacter: 'P' }
      } else if (this.packageShow) {
        param = { inputCharacter: 'B' }
      } else if (this.otherShow) {
        param = { inputCharacter: 'W' }
      }
      putAction(url, param).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
        }
      })
    },
    //选择员工方法
    handleSelectEmployeeOk(data) {
      console.log('选择员工：', data)
      if (data) {
        this.model.belongUser = data.employeeName
        this.$forceUpdate() //重新渲染UI
      }
    },
    //绑定所属员工
    handleSelectEmployee() {
      this.$refs.selectEmployee.visible = true
    },
    //计算转换率
    noneSpecChange() {
      try {
        console.log(this.productShow || this.otherShow, '产品或包材')
        if (this.productShow || this.otherShow) {
          this.model.noneSpec = this.model.noneSpec.toUpperCase().trim()
          let tempSpec = this.model.noneSpec
          let k = tempSpec.indexOf('KG')
          let k1 = tempSpec.indexOf('G')

          let l1 = tempSpec.indexOf('ML')
          let l2 = tempSpec.indexOf('L')
          let c = tempSpec.indexOf('*')
          let t2 = tempSpec.substr(c + 1)
          console.log(c, t2, 'c-t2')
          let bt2 = c && c > -1 ? Number.parseFloat(t2) : 1
          if (k > 0) {
            let t1 = tempSpec.substr(0, k)
            let bt1 = Number.parseFloat(t1)

            this.model.packSpec = (bt1 * bt2 * 1000).toFixed(0)
            this.model.coRate = ((bt1 * bt2) / 1000).toFixed(6)
          } else if (k1 > 0) {
            let t1 = tempSpec.substr(0, k1)
            let bt1 = Number.parseFloat(t1)

            this.model.packSpec = (bt1 * bt2).toFixed(0)
            this.model.coRate = ((bt1 * bt2) / 1000000).toFixed(6)
          } else if (l1 > 0) {
            let t1 = tempSpec.substr(0, l1)
            let bt1 = Number.parseFloat(t1)

            this.model.packSpec = (bt1 * bt2).toFixed(0)
            this.model.coRate = ((bt1 * bt2) / 1000000).toFixed(6)
          } else if (l2 > 0) {
            let t1 = tempSpec.substr(0, l2)
            let bt1 = Number.parseFloat(t1)
            this.model.packSpec = (bt1 * bt2 * 1000).toFixed(0)
            this.model.coRate = ((bt1 * bt2) / 1000).toFixed(6)
          }
        } else {
          this.model.packSpec = 0
          this.model.coRate = 0
        }
        this.nameChange()
      } catch (e) {}
    },
    onWarehouseSelected(rows) {
      this.model.warehouseCode = rows.warehouseCode
      this.model.warehouseName = rows.warehouseName
    },
    //根据新增物料主数据时选中的物料类别判断展示列
    onGoodsCategorySelected(rows) {
      this.model.categoryName = rows.name
      this.model.categoryNo = rows.code
      this.loadingGoodsCategory()
    },
    //根据物料类别判断展示列
    loadingGoodsCategory() {
      // 判断是否是成品，并且关联包材，如果是下方显示包材关联表
      let str = this.model.categoryName
      let code = this.model.categoryNo
      let productChar = '成品'
      let packageChar = '包材'
      let otherChar = '原料'
      let containsProductChar = str.includes(productChar)
      let containsPackageChar = str.includes(packageChar)
      let containsOtherChar = str.includes(otherChar)
      if (containsProductChar) {
        console.log('containsProductChar')
        this.productShow = true
        this.otherShow = false
        this.packageShow = false
      } else if (containsPackageChar) {
        console.log('containsPackageChar')
        this.productShow = false
        this.otherShow = false
        this.packageShow = true
      } else {
        console.log('containsOtherChar')
        this.productShow = false
        this.otherShow = true
        this.packageShow = false
      }
      if (this.packageShow) {
        this.validatorRules = {
          code: [{ required: true, message: '请输入编号!' }],
          noneSpec: [{ required: true, message: '请输入规格!' }],
          packSpec: [{ required: false, message: '请输入包装规格(g)!' }],
          categoryName: [{ required: true, message: '请输入物料种类!' }],
          customCode: [{ required: false, message: '请输入客户物料编号!' }],
          meUnit: [{ required: true, message: '请输入计量单位!' }],
          auUnit: [{ required: false, message: '请选择辅单位' }],
          useStatus: [{ required: true, message: '请输入状态!' }],
          coRate: [{ required: false, message: '请输入转化率' }],
          classificationId: [{ required: true, message: '请输入物料分类!' }],
          isPattern: [{ required: false, message: '请输入是否有版样!' }],
          stockQuantity: [{ required: false, message: '请输入安全库量!' }],
          inventoryQuantity: [{ required: false, message: '请输入库存数量!' }],
          warehouseCode: [{ required: true, message: '请输入所属仓库!' }],
          isAssBc: [{ required: false, message: '请输入是否关联包材!' }],
          isPublic: [{ required: false, message: '请输入是否公用!' }],
          isUse: [{ required: false, message: '请输入是否领料!' }],
        }
      } else {
        this.validatorRules = {
          code: [{ required: true, message: '请输入编号!' }],
          noneSpec: [{ required: true, message: '请输入规格!' }],
          packSpec: [{ required: false, message: '请输入包装规格(g)!' }],
          categoryName: [{ required: true, message: '请输入物料种类!' }],
          customCode: [{ required: false, message: '请输入客户物料编号!' }],
          meUnit: [{ required: true, message: '请输入计量单位!' }],
          auUnit: [{ required: true, message: '请选择辅单位' }],
          useStatus: [{ required: true, message: '请输入状态!' }],
          coRate: [{ required: true, message: '请输入转化率' }],
          classificationId: [{ required: true, message: '请输入物料分类!' }],
          isPattern: [{ required: false, message: '请输入是否有版样!' }],
          stockQuantity: [{ required: false, message: '请输入安全库量!' }],
          inventoryQuantity: [{ required: false, message: '请输入库存数量!' }],
          warehouseCode: [{ required: true, message: '请输入所属仓库!' }],
          isAssBc: [{ required: false, message: '请输入是否关联包材!' }],
          isPublic: [{ required: false, message: '请输入是否公用!' }],
          isUse: [{ required: false, message: '请输入是否领料!' }],
        }
      }
    },
    onChangeShowRow() {
      getAction('/goods/erpGoodsCategory/queryByCode', { code: this.model.categoryNo }).then((res) => {
        if (res.success) {
          let str = res.result.name
          let char = '成品'
          let containsChar = str.includes(char)
          if (containsChar && (this.model.isAssBc === 1 || this.model.isAssBc === '1')) {
            this.productShow = true
          } else {
            this.productShow = false
          }
        }
      })
    },
    onSelectChange() {},
    onSelectRow() {},
    add() {
      this.loadingGoodsCategory()
      this.getGoodsCode()
      this.model.belongUser=store.getters.userInfo.realname
      //this.visible == true
    },
    edit(record) {
      this.model = Object.assign({}, record)
      this.loadingGoodsCategory()
      console.log('编辑', this.productShow, this.model)
      if (this.productShow) {
        //获取配方列表
       this.getFormulas()
        this.getPackages()
      }
    },
    getFormulas(){
      getAction('/base/erpGoodsFormula/queryByGoodsId', { goodsId: this.model.id }).then((res) => {
          this.formulaTable.datasource = res.result
          console.log('配方列表', res.result)
          this.$forceUpdate()
        })
    },
    getPackages() {
      getAction('/base/erpGoods/queryErpGoodsPackageByMainId', { goodsId: this.model.id }).then((res) => {
        console.log('包材列表', res.result)
        this.model.erpGoodsPackageList = res.result
        this.$forceUpdate()
      })
    },
    updatePackageOk() {
      this.getPackages()
    },
    submitForm() {
      const that = this
      console.log('提交', this.model)
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    // addRowCustom () {
    //   this.orderMainModel.jeecgOrderCustomerList.push({});
    //   this.$forceUpdate();
    // },
    goodsOk(datas) {
      let _this = this
      const pids = _this.model.erpGoodsPackageList.map((item) => item.packageId)
      console.log('-----------------------')
      console.log(datas, pids)
      postAction('/base/erpGoods/list/ids', { ids: datas }).then((res) => {
        let erpGoodsList = res.result
        erpGoodsList.forEach(function (item, index) {
          if (pids.indexOf(item.id) > -1) {
            console.log('选择重复包材！', item.id)
            return
          }
          let detail = {}
          detail.packageId = item.id
          detail.packageCode = item.code
          detail.packageName = item.name
          detail.noneSpec = item.noneSpec
          detail.packageCategory = item.packageCategory
          detail.proportion = item.proportion
          detail.brand = item.brand
          detail.itemName = item.itemName
          detail.flavor = item.flavor
          detail.background = item.background
          detail.materialQuality = item.materialQuality
          _this.model.erpGoodsPackageList.push(detail)
          console.log('新增包材', _this.model.erpGoodsPackageList)
        })
        _this.$forceUpdate()
      })
    },
    filterPackageId(packageId) {
      this.model.erpGoodsPackageList = this.model.erpGoodsPackageList.filter(function (item) {
        return item.packageId !== packageId
      })
    },
    //添加已有包材
    addMaterielPackage: function () {
      this.$nextTick(() => {
        this.$refs.selectGoodsList.add()
      })
    },
    //新增包材
    newMaterielPackage() {
      this.$nextTick(() => {
        this.$refs.addGoodsPackage.add()
      })
    },
    //编辑包材信息
    onEditPackage(record) {
      this.$nextTick(() => {
        this.$refs.addGoodsPackage.edit(record)
      })
    },
    onCellChange(record, dataIndex, value) {
      const dataSource = [...this.model.erpGoodsPackageList]
      const target = dataSource.find((item) => item.packageCode === record.packageCode)
      if (record) {
        target[dataIndex] = value
        this.model.erpGoodsPackageList = dataSource
        console.log('修改包材属性', record, dataIndex, value, this.model.erpGoodsPackageList)
        this.$forceUpdate()
      }
    },
    onDelete(key) {
      const dataSource = [...this.model.erpGoodsPackageList]
      this.model.erpGoodsPackageList = dataSource.filter((item) => item.packageId !== key)
      this.$forceUpdate()
    },
    copy(record) {
      console.log(record)
      this.model = Object.assign({}, record)
      this.model.id = undefined
      this.loadingGoodsCategory()
      this.getGoodsCode()
    },
  },
}
</script>
